﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace CPPEI.Utility
{
    public class SerializeUtility
    {
        public static byte[] SerializeToBinary(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(ms, obj);

                byte[] resbytes = new byte[ms.Length];

                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(resbytes, 0, (int)ms.Length);

                return resbytes;
            }
        }

        /// <summary>
        /// 将对象序列化到文件中，如果文件存在会被覆盖，不存在会创建
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filePath"></param>
        public static void SerializeToBinaryFile(object obj, string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            if (fi.Exists)
            {
                fi.Delete();
            }
            else
            {
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
            }

            using (FileStream ms = new FileStream(filePath, FileMode.CreateNew))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(ms, obj);
            }
        }

        public static object DeserializeFromBinary(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                return binaryFormatter.Deserialize(ms);
            }
        }

        /// <summary>
        /// 从二进制文件反序列化成对象
        /// </summary>
        /// <param name="filePath">文件完整路径</param>
        /// <returns></returns>
        public static object DeserializeFromBinaryFile(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                try
                {
                    object obj = binaryFormatter.Deserialize(fs);
                    return obj;
                }
                catch
                {
                    return null;
                }
            }
        }
    }
}
